package com.itheima.contorller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domian.Category;
import com.itheima.domian.MyPage;
import com.itheima.mapper.admin.CategoryMapper;
import com.itheima.service.impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 12441
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryServiceImpl categoryService;


    @PostMapping
    public R<Category> addCategory(@RequestBody Category category) {

        log.info("-------------------"+category.toString());

        categoryService.save(category);
        return R.success(category, "'分类名'已存在");

    }

    //    @GetMapping
//    public R<Category> addCategory(HttpServletRequest httpServletRequest){
//
//        String type = httpServletRequest.getParameter("type");
//
//
//
//        categoryMapper.insert(category);
//        return R.success(category,"'分类名'已存在");
//
//    }
    @GetMapping("/page")
    public R<MyPage> page(HttpServletRequest httpServerRequest) {


        MyPage myPage = new MyPage();

        Integer page = Integer.valueOf(httpServerRequest.getParameter("page"));
        Integer size = Integer.valueOf(httpServerRequest.getParameter("pageSize"));


        IPage ipage = new Page(page, size);

        categoryMapper.selectPage(ipage, null);

        //查询数据ipage.getRecords();
        long total = ipage.getTotal();
        if (total == 0) {

            return R.error("无数据");
        }
        myPage.setRecords(ipage.getRecords());
        myPage.setTotal(ipage.getTotal());
        log.info(String.valueOf(ipage.getRecords()));
        myPage.setSize(size);
        myPage.setCurrent(page);

        return R.success(myPage, "查询完成");

    }

    @DeleteMapping
    public R<Category> deleteCategory(HttpServletRequest httpServletRequest) {
        String id = httpServletRequest.getParameter("id");

        categoryService.removeById(id);

        return R.success("成功");
    }
    @PutMapping
    public R<Category> editCategory(@RequestBody Category category){
        categoryMapper.updateById(category);
        return R.success(category,"success");
    }
    @GetMapping("/list")
    public R<List<Category>>showList(HttpServletRequest httpServletRequest){
        int type = Integer.parseInt(httpServletRequest.getParameter("type"));
        List<Category> categories = categoryService.selectByType(type);
        return R.success(categories,"查询成功");
    }
}
